﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;


namespace ZX.WebApp.Crm.BasePages
{
    public partial class Affix : System.Web.UI.Page
    {
        public bool statue = false;
        public string workinsid = "";
        public string worktasid = "";
        private string[] fieldList ={ "AffixId", "WorkflowId", "WorkflowInsId", "WorktaskId", "WorktaskInsId",
                                "FileNameId","FileName","FilePath"};
        ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient();
        public string WorkflowInsId
        {
            get
            {

                string _WorkflowInsId = Session["workinsid"].ToString();
                if (_WorkflowInsId == "")
                {
                    _WorkflowInsId = Guid.NewGuid().ToString();
                }
                return _WorkflowInsId;
            }
            set
            {
                Session["workinsid"] = value;
            }

        }
        public string WorkTaskInsId
        {
            get
            {

                string _WorkTaskInsId = Session["WorkTaskInsId"].ToString();
                if (_WorkTaskInsId == "")
                {
                    _WorkTaskInsId = Guid.NewGuid().ToString();
                }
                return _WorkTaskInsId;
            }
            set
            {
                Session["WorkTaskInsId"] = value;
            }

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //base.Page_Load();
            if (!IsPostBack)
            {
                //Session["workinsid"] = Guid.NewGuid().ToString();
                //Session["worktasid"] = Guid.NewGuid().ToString();
                InitData();
            }
        }
        private void InitData()
        {
            string guidvalue = string.Empty;
            
            if (Request["WorkFlowInstanceId"].ToString() != "")
            {
               // System.Drawing.Color.#76becc
               // System.Drawing.Color.Empty
                statue = true;
                guidvalue = Request["WorkFlowInstanceId"].ToString();
            }
            else
            {
                statue = false;
                guidvalue = WorkflowInsId;
            }
            if (Request["Status"].ToString() == "3")
            {
                inputFile.Disabled = true;
                ButtonConfirm.Enabled = false;
            }
            DataTable dt = client.GetAffixTable(guidvalue,statue);
            if (dt.Rows.Count > 0)
            {
                gvAffixfiles.DataSource = dt;
                gvAffixfiles.DataBind();
            }
            else 
            {
                gvAffixfiles.DataSource = null;
                gvAffixfiles.DataBind();
            }
            return;
        }
        protected void ButtonConfirm_Click(object sender, EventArgs e)
        {
            //检查上传文件不为空
            if (inputFile.PostedFile.ContentLength <= 5242880 && inputFile.PostedFile.ContentLength >0)
            {
                //设定上传文件的保存路径
                string strSaveDir = "../Files/";
                string strName = this.inputFile.PostedFile.FileName;
                //取得文件名(抱括路径)里最后一个"."的索引
                int intExt = strName.LastIndexOf(".");

                //取得文件扩展名
                string strExt = strName.Substring(intExt);
                //这里我自动根据日期和文件大小不同为文件命名,确保文件名不重复


                string filetype=strExt.Replace(".","");
                filetype=filetype.ToUpper();
                if (filetype == "JS" || filetype == "EXE" || filetype == "MSI")
                {
                    inputFile.Focus();
                    labelUpResult.Text = "上传文件不能包脚文件与执行文件！";
                    return;
                }
                else
                {
                    //取得文件名(包括路径)里最后一个"\"的索引
                    int intPath = strName.LastIndexOf("\\");
                    //取得文件名(不包括路径)
                    string strNewName = strName.Substring(intPath + 1);
                    string filenameid = Guid.NewGuid().ToString();
                    //保存文件到你所要的目录,这里是IIS根目录下的upload目录.你可以改变.
                    //注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里"\"必须用"\\"代替
                    string filenamepath = Server.MapPath(strSaveDir + filenameid + strExt);
                    this.inputFile.PostedFile.SaveAs(filenamepath);
                    //得到这个文件的相关属性:文件名,文件类型,文件大小
                    labelUpResult.Text = "上传成功！";
                    //labelFileName.Text = "文件源：" + strName;
                    //labelFileExt.Text = "文件类型：" + inputFile.PostedFile.ContentType + "( " + strExt + " )";
                    //labelFileSize.Text = "文件大小：" + (inputFile.PostedFile.ContentLength / 1024).ToString() + " K Byte(s)";
                    CrmWorkFlowService.AffixFiles entity = new CrmWorkFlowService.AffixFiles();
                    entity.AffixId = filenameid;
                    entity.WorkflowId = Request["WorkflowId"].ToString();
                    if (Request["WorkFlowInstanceId"].ToString() != "")
                    {
                        entity.WorkflowInsId = Request["WorkFlowInstanceId"].ToString();
                    }
                    else
                    {
                        entity.WorkflowInsId = WorkflowInsId;
                    }
                    entity.WorktaskId = Request["WorktaskId"].ToString();
                    entity.WorktaskInsId = WorkTaskInsId;// Convert.ToString(Session["worktasid"]);
                    entity.FileNameId = filenameid + strExt;
                    entity.FileName = strNewName;
                    entity.FilePath = filenamepath;
                    client.InsertAffixcrm(entity);
                    labelUpResult.Text = "上传成功！";
                    InitData();
                    return;
                }

            }
            else if (inputFile.PostedFile.ContentLength > 5242880)
            {
                labelUpResult.Text = "上传文件不能大于5M！";
                return;
            }
        }
        public static void OpenWindowInNewPage(Page curPage, string destUrl)
        {
            string scriptString = string.Format("<script language='JavaScript'>window.open('" + "{0}" + "','_new','toolbar=no,resizable=yes,scrollbars=yes');<", destUrl);
            scriptString += "/";
            scriptString += "script>";
            if (!curPage.IsStartupScriptRegistered("Startup"))
            {
                curPage.RegisterStartupScript("Startup", scriptString);
            }
            return;
        }
        protected void lbtnFileName_Click(object sender, EventArgs e)
        {
            string parms = (sender as LinkButton).CommandArgument.ToString();
            string name = (sender as LinkButton).CommandName.ToString();
            dFile(parms, name);
            return;
        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            string parms = (sender as LinkButton).CommandArgument.ToString();
            string name = (sender as LinkButton).CommandName.ToString();
            dFile(parms, name);
            return;
        }
        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            
            BaseUserControl buc = new BaseUserControl();
            if (buc.CtrlState == WorkFlowConst.STATE_VIEW)
                return;
            string[] parms = (sender as LinkButton).CommandArgument.Split(',');
            int i =client.DeleteAffix(parms[0]);//删除数据库记录文件
            if (i > 0)
            {
                labelUpResult.Text = "删除成功！";
            }
            File.Delete(parms[1]);
            InitData();

        }
        protected void dFile(string parms,string name)
        {
            //判断是否选择文件名
            if (parms != "")
            {
                //获取文件路径
                string path = Server.MapPath("../") + "Files\\" + parms;

                //初始化 FileInfo 类的实例，它作为文件路径的包装
                FileInfo fi = new FileInfo(path);
                //判断文件是否存在
                if (fi.Exists)
                {
                   // ////将文件保存到本机上
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
                    Response.AddHeader("Content-Length", fi.Length.ToString());
                    Response.AddHeader("Content-Transfer-Encoding", "binary");
                    Response.ContentType = "application/octet-stream";
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    Response.WriteFile(fi.FullName);
                    Response.Flush();
                    Response.End();


                    ////以字符流的形式下载文件 
                    //FileStream fs = new FileStream(path, FileMode.Open);

                    //byte[] bytes = new byte[(int)fs.Length];

                    //fs.Read(bytes, 0, bytes.Length);

                    //fs.Close();
                    //Response.Clear();
                    //Response.ClearContent();
                    //Response.ClearHeaders();
                    //Response.AddHeader("Content-Length", bytes.Length.ToString());
                    //Response.ContentType = "application/octet-stream";
                    ////通知浏览器下载文件而不是打开 
                    //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
                    ////Response.AddHeader("Content-Disposition", "attachment; filename=" + name);
                    //Response.BinaryWrite(bytes);
                    //Response.Flush();
                    //Response.End();
               }
            }
            else
            {
                Page.RegisterStartupScript("sb1", "<script>alert('请先选择需要下载的文件，谢谢！')</script>");
            }
        }




    }
}